package com.linkkap.feishu.api.controller.robot;

import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;

import cn.hutool.core.io.IORuntimeException;
import com.linkkap.feishu.api.msg.EventRollbackType;
import com.linkkap.feishu.api.msg.MessageResources;
import com.linkkap.feishu.api.service.EventTypeFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.linkkap.feishu.api.helper.FeiShuHelper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@Api(value = "机器人接口", tags = {"机器人"})
public class FeiShuRobotController {

	private final static String APP_ID     = "cli_a0b70a2e3cf8d00b";
	private final static String APP_SECRET = "c90JuD4JTR7G5hZn7I3LogWW8rbyRRq8";

	private final static String APP_VERIFICATION_TOKEN = "zRMfwyUdZSBbtzvlkvKIldOxB0glkON5";
	@Autowired
	EventTypeFileService fileService;
	//这里报回字符串类型的数据，飞书会报返回的结构不符合JSON格式
    @ResponseBody
	@RequestMapping(value="/feishu/robot.do", method = RequestMethod.POST, produces =  MediaType.APPLICATION_JSON_VALUE)
    @ApiOperation(value = "接收消息", notes = "接收飞书发过来的消息")
    public JSONObject  robot(@RequestBody Map<String,String> jsonParam) {
        // 直接将json信息打印出来
		log.debug("接收到的参数"+jsonParam.toString());
		
		String type  = jsonParam.get("type");
		String token = jsonParam.get("token");
		
		if(!token.equals(APP_VERIFICATION_TOKEN)) {
			log.error("接到的请求token不对，返回空字符串.");
			return null;
		}
		log.info("接收到的请求类型:"+type);
		if("url_verification".equals(type)) {
			
			String challenge = jsonParam.get("challenge");
			
	        // 将获取的json数据封装一层，然后在给返回
	        JSONObject result = new JSONObject();
	        result.put("challenge",challenge);
	 
	        return result;
		}
		
		if("event_callback".equals(type)) {
            //获取事件内容和类型，并进行相应处理，此处只关注给机器人推送的消息事件
            String event = jsonParam.get("event");
            JSONObject jsonEvent = JSON.parseObject(event);
            String evenType = jsonEvent.getString("type");
            JSONObject resquest;
            if(EventRollbackType.TYPES.contains(evenType)){
				try {
					String openId = jsonEvent.getString("open_id");
					//根据KEY从文件中获取对应的内容
					String key = evenType;
					log.info("返回的回调事件类型: {}", evenType);
					String content = fileService.getStringByKey(key);
					log.info("即将要返回的数据：{}", content);
					String accessToken  = FeiShuHelper.getTenantAccessToken(APP_ID, APP_SECRET);
					//重文件夹中获取数据
					resquest = JSONObject.parseObject(content);
					resquest.put("open_id", openId);
					//只针对对应的用户传送消息
					FeiShuHelper.sendContentMessage(accessToken, resquest.toString());
				}catch (IORuntimeException e){
					return null;
				} catch (Exception e) {
					e.printStackTrace();
				}
            }
		}
		return null;
    }
	/**
	 *
	 * @param data 封装好的数据 {“EventRollbackType”: ..., "content": "富文本内容"}
	 * @return void
	 * @author huang_qiu_sheng
	 * @date 3/12/2021 5:42 PM
	 */
	@RequestMapping(value="/feishu/eventRollbackType.do", method = RequestMethod.POST, produces =  MediaType.APPLICATION_JSON_VALUE)
	@ApiOperation(value = "变更回调的事件类型", notes = "变更回调的事件类型")
	public void  saveEventRollbackType(@RequestBody Map<String,String> data) {
    	String key = data.get("event_type");
    	String content = data.get("content");
		log.debug("更改的回调数据类型: {}", key);
		if(EventRollbackType.TYPES.contains(key)){
			log.debug("内容为：{}", content);
			fileService.saveStringByKey(key, content);
		}else{
			log.debug("更改的回调数据类型不存在");
		}
	}
	/**
	 *
	 * @param data
	 * @return void
	 * @author huang_qiu_sheng
	 * @date 3/12/2021 5:45 PM
	 */
	@RequestMapping(value="/feishu/eventRollbackType.do", method = RequestMethod.DELETE, produces =  MediaType.APPLICATION_JSON_VALUE)
	@ApiOperation(value = "删除回调的事件类型", notes = "删除回调的事件类型")
	public void  deleteEventRollbackType(@RequestBody Map<String, String> data) {
		String key =  data.get("event_type");
		log.debug("删除回调的事件类型: {}", key);
		if(EventRollbackType.TYPES.contains(key)) {
			fileService.removeStringByKey(key);
		}else{
			log.debug("删除的回调的事件类型不存在");
		}
	}
}
